<?php

namespace Tools\Root\HttpClient\Clients;

use Tools\Root\HttpClient\BaseClient;

/**
 * Class HanZiClient
 *
 * @package Tools\Root\HttpClient\Clients
 */
final class HanZiClient extends BaseClient
{
    /**
     * Initialize
     *
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Exception
     */
    public function initialize()
    {
        parent::initialize();

        // token handle
        if ($this->loader->get('token', false) === false ||
            $this->loader->get('Authorization', false) === false) {
            $this->tokenHandle();
        }

        // header
        $this->serviceConfig['headers'] = [
            'Authorization' => $this->loader->get('Authorization', ''),
            'X-ISAPI' => 1,
            'X-VERSION' => 1.1,
        ];
    }

    /**
     * Get token.
     *
     * @param string $path
     * @param string $method
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getToken(string $path = 'api/init', string $method = 'GET')
    {
        $response = $this->client->request($method, $path);

        $content = $response->getBody()->getContents();
        if ($content !== '') {
            $data = json_decode($content, false,512, JSON_UNESCAPED_UNICODE);

            if ($data->result && $data->token !== '') return $data->token;
        }

        throw new \Exception('Get token failure!');
    }

    /**
     * Handle token.
     *
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function tokenHandle()
    {
        $token = $this->getToken();

        $this->loader->set('token', $token);
        $this->loader->set('Authorization', $token);
    }

    /**
     * Service status.
     *
     * @param string $path
     * @param string $method
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Exception
     */
    public function status(string $path = 'api/status', string $method = 'GET') : bool
    {
        if (!parent::status()) return false;

        try {
            $data = $this->request($method, $path);
        } catch (\Exception $exception) {
            return false;
        }

        return $data->status;
    }
}
